package net.mhelvens.deltaprofiles;

import net.mhelvens.deltaprofiles.R;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;

public class MainRuleListFragment extends ListFragment {
	@SuppressWarnings("unused") private static final String TAG = MainRuleListFragment.class.getSimpleName();
	
	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		startActivity(
			new Intent(RuleEditActivity.EDIT_RULE, null, this.getActivity(), RuleEditActivity.class)
				.putExtra("id", id)
		);
		super.onListItemClick(l, v, position, id);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setHasOptionsMenu(true);
	}
	
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.fragment_rule_list, menu);
		super.onCreateOptionsMenu(menu, inflater);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case R.id.new_rule: {
				startActivity(
					new Intent(RuleEditActivity.NEW_RULE, null, this.getActivity(), RuleEditActivity.class)
				);
				return true;
			}
		}
		return super.onOptionsItemSelected(item);
	}
	
	private void refresh() {
		setListAdapter(Rule.all(
			Rule.Adapter.FLAG_NAME        |
			Rule.Adapter.FLAG_DESCRIPTION |
			Rule.Adapter.FLAG_ICON
		));
	}
	
	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		this.setEmptyText(getString(R.string.no_rules_message));
	}

	@Override
	public void onResume() {
		super.onResume();
		refresh();
	}
	
}
